package com.hjq.fcloud.utils

import android.content.Context
import android.text.TextUtils
import com.hjq.fcloud.bean.CommonFileBean
import com.hjq.toast.ToastUtils
import top.zibin.luban.CompressionPredicate
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import top.zibin.luban.OnRenameListener
import java.io.File

/**
 * 图片压缩帮助类
 */
class ZipImageUtils {

    /**
     * 压缩单张图片
     */
    fun zipImages(
        context: Context,
        filePath: String,
        callBack: (zipSuccess: Boolean, errorMsg: String?, zipImgList: List<CommonFileBean>?) -> Unit
    ) {
        var filePaths = ArrayList<CommonFileBean>()
        filePaths.add(CommonFileBean(filePath))
        zipImages(context, filePaths, callBack)
    }

    /**
     * 压缩图片
     */
    fun zipImages(
        context: Context,
        filePaths: List<CommonFileBean>,
        callBack: (zipSuccess: Boolean, errorMsg: String?, zipImgList: List<CommonFileBean>?) -> Unit
    ) {
        if (filePaths == null || filePaths.size == 0) {
            callBack(false, "文件列表为空", null)
            return
        }

        //缓存压缩图片路径
        var cacheDir = context.getCacheDir().absolutePath

        var count = 0;
        filePaths.forEach {
            Luban.with(context)
                .load(it.url)
                .setTargetDir(cacheDir)
                .filter(object : CompressionPredicate {
                    override fun apply(path: String?): Boolean {
                        return !(TextUtils.isEmpty(path))
                    }
                })
                .setRenameListener(object : OnRenameListener {
                    override fun rename(str: String): String {
                        return FileUtils.getFileName(str)
                    }
                })
                .setCompressListener(object : OnCompressListener {
                    override fun onStart() {}
                    override fun onSuccess(file: File) {
                        it.url = file.absolutePath
                        count++
                        if (count == filePaths.size) {
                            callBack(true, null, filePaths)
                        }
                    }

                    override fun onError(e: Throwable) {
                        callBack(false, "图片压缩失败", null)
                    }
                }).launch()
        }
    }

}